/* @vitest-environment node */ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn(), })); import { getSession } from "@/lib/auth/session"; import { GET } from "./route.js"; describe("GET /api/branches/[branch]/[year]/[month]/days", () => { let tmpRoot; const originalNasRoot = process.env.NAS_ROOT_PATH; beforeEach(async () => { vi.clearAllMocks(); tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), "api-days-")); process.env.NAS_ROOT_PATH = tmpRoot; await fs.mkdir(path.join(tmpRoot, "NL01", "2024", "10", "23"), { recursive: true, }); }); afterEach(async () => { process.env.NAS_ROOT_PATH = originalNasRoot; if (tmpRoot) await fs.rm(tmpRoot, { recursive: true, force: true }); }); it("returns 401 when unauthenticated", async () => { getSession.mockResolvedValue(null); const res = await GET( new Request("http://localhost/api/branches/NL01/2024/10/days"), { params: Promise.resolve({ branch: "NL01", year: "2024", month: "10" }), } ); expect(res.status).toBe(401); expect(await res.json()).toEqual({ error: "Unauthorized" }); }); it("returns 403 when branch user accesses a different branch", async () => { getSession.mockResolvedValue({ role: "branch", branchId: "NL01", userId: "u1", }); const res = await GET( new Request("http://localhost/api/branches/NL02/2024/10/days"), { params: Promise.resolve({ branch: "NL02", year: "2024", month: "10" }), } ); expect(res.status).toBe(403); expect(await res.json()).toEqual({ error: "Forbidden" }); }); it("returns days for a valid branch/year/month when allowed", async () => { getSession.mockResolvedValue({ role: "admin", branchId: null, userId: "u2", }); const res = await GET( new Request("http://localhost/api/branches/NL01/2024/10/days"), { params: Promise.resolve({ branch: "NL01", year: "2024", month: "10" }), } ); expect(res.status).toBe(200); const body = await res.json(); expect(body).toEqual({ branch: "NL01", year: "2024", month: "10", days: ["23"], }); }); it("returns 400 when any param is missing (authenticated)", async () => { getSession.mockResolvedValue({ role: "admin", branchId: null, userId: "u2", }); const res = await GET( new Request("http://localhost/api/branches/NL01/2024//days"), { params: Promise.resolve({ branch: "NL01", year: "2024", month: undefined, }), } ); expect(res.status).toBe(400); expect(await res.json()).toEqual({ error: "branch, year oder month fehlt", }); }); });